import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/entity/home/news_comment_entity.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/resources/styles.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/module/home/comments/comment_input.dart';
import 'package:ball_lion/widgets/circular.dart';
import 'package:ball_lion/widgets/loading/loading_widget.dart';
import 'package:ball_lion/server/api/home_api.dart';
import 'package:ball_lion/utils/toast_utils.dart';
import 'package:ball_lion/widgets/base/wqs_text.dart';
import 'comment_Item.dart';

class CommentSheet extends StatefulWidget {
  const CommentSheet(
      {super.key,
      required this.comment,
      required this.newsId,
      this.focus = false});

  final NewsCommentEntity? comment;
  final int newsId;
  final bool focus;

  static show(NewsCommentEntity? comment, int newsId, bool reply) {
    Get.bottomSheet(
      CommentSheet(
        comment: comment,
        newsId: newsId,
        focus: reply,
      ),
      isScrollControlled: true,
    );
  }

  @override
  State<CommentSheet> createState() => _CommentSheetState();
}

class _CommentSheetState extends State<CommentSheet> {
  late NewsCommentEntity? origin = widget.comment;
  int get newsId => widget.newsId;
  List<NewsCommentEntity>? comments;
  int commentIndex = 1;
  EasyRefreshController refreshController =
      EasyRefreshController(controlFinishLoad: true);
  final FocusNode inputFocus = FocusNode();
  NewsCommentEntity? _commentAt;

  NewsCommentEntity? get commentAt => _commentAt;

  set commentAt(NewsCommentEntity? value) => setState(() => _commentAt = value);

  Future getComments() async {
    commentIndex = 1;
    comments = await HomeApi.getCommentList(newsId,
        page: commentIndex, originId: origin?.id);
    setState(() {});
  }

  Future loadComments() async {
    commentIndex += 1;
    final r = await HomeApi.getCommentList(newsId,
        page: commentIndex, originId: origin?.id);
    if (r.hasValue) {
      comments?.addAll(r);
    }
    refreshController.finishLoad((comments?.length ?? 0) < commentIndex * 20
        ? IndicatorResult.noMore
        : IndicatorResult.success);
    setState(() {});
  }

  Future report(NewsCommentEntity comment, String reason, [int? index]) async {
    var r = await HomeApi.support(comment.id ?? 0, type: 2, newsId: newsId);
  }

  Future changeLike(int like, [int? index]) async {
    var comment = index != null ? comments![index] : origin;
    var r = await HomeApi.support(comment?.id ?? 0,
        type: like == 1 ? 1 : 3, newsId: newsId);
    if (r == 200) {
      comment?.isLike = like;
      if (comment?.likeNum.hasValue ?? false) {
        comment!.likeNum = comment.likeNum! + (like == 1 ? 1 : -1);
      } else {
        if (like == 1) {
          comment?.likeNum = 1;
        }
      }
    }
    setState(() {});
  }

  Future delete(NewsCommentEntity comment, [int? index]) async {
    var r = await HomeApi.deleteComment(comment.id ?? 0);
    if (r == 200) {
      if (index != null) {
        comments?.removeAt(index);
      }
    }
    setState(() {});
  }

  void reply(NewsCommentEntity comment) {
    commentAt = comment;
    inputFocus.requestFocus();
  }

  Future sendChat(
      TextEditingController textController, FocusNode inputFocus) async {
    if (textController.text.noValue) {
      Toast.text("发言内容不能为空");
      return;
    }
    final r = await HomeApi.add(newsId, textController.text,
        fromId: commentAt?.id, originId: origin?.id);
    if (r.data['c'] == 200) {
      final c = NewsCommentEntity.fromJson(r.data['d']);
    }
    textController.clear();
    inputFocus.unfocus();
    setState(() {});
  }

  @override
  void initState() {
    commentAt = origin;
    getComments();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return DraggableScrollableSheet(
      minChildSize: 0.75,
      initialChildSize: (Get.height - Get.mediaQuery.padding.top) / Get.height,
      maxChildSize: (Get.height - Get.mediaQuery.padding.top) / Get.height,
      builder: (BuildContext context, ScrollController scrollController) =>
          Circular(
        borderRadius: const BorderRadius.vertical(top: Radius.circular(13)),
        color: Colours.white,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                GestureDetector(
                  onTap: navigator?.pop,
                  child: Container(
                    padding: const EdgeInsets.fromLTRB(16, 10, 0, 10),
                    alignment: Alignment.topLeft,
                    child: Image.asset(Utils.getImgPath('arrow_back.png'),
                        width: 24, height: 24),
                  ),
                ),
                const Spacer(),
                const QsText("回复",
                    fontSize: 18,
                    fontWeight: FontWeight.w500,
                    color: Colours.text),
                const Spacer(),
                Container(
                  padding: const EdgeInsets.fromLTRB(16, 10, 0, 10),
                  alignment: Alignment.topLeft,
                  child: const SizedBox(width: 24),
                ),
              ],
            ),
            const Divider(height: 0.5, color: Colours.greyEE),
            if (origin != null) ...[
              CommentItem(
                newsId: newsId,
                isSecondary: true,
                isOrigin: true,
                comment: origin,
                onReport: (String reason) => report(origin!, reason),
                onLike: changeLike,
                onDelete: () => delete(origin!),
                onReply: () => reply(origin!),
              ).paddingSymmetric(horizontal: 16),
              const Divider(height: 0.5, color: Colours.greyEE),
            ],
            const QsText(
              "全部回复",
              fontSize: 16,
              fontWeight: FontWeight.w500,
            ).paddingOnly(top: 16, left: 16, bottom: 16),
            Expanded(
              child: EasyRefresh.builder(
                controller: refreshController,
                scrollController: scrollController,
                onLoad: loadComments,
                footer:
                    Styles.refreshFooter(position: IndicatorPosition.locator),
                childBuilder: (BuildContext context, ScrollPhysics physics) {
                  return CustomScrollView(
                    physics: physics,
                    controller: scrollController,
                    slivers: [
                      SliverToBoxAdapter(child: Container(height: 10)),
                      LoadingWidget<bool>.sliver(
                        isLoading: comments == null,
                        data: comments?.length == 0,
                        child: () => SliverList.builder(
                            itemCount: comments?.length,
                            itemBuilder: (context, index) {
                              return Container(
                                color: Colours.white,
                                padding:
                                    const EdgeInsets.symmetric(horizontal: 16),
                                child: CommentItem(
                                  isSecondary: true,
                                  newsId: newsId,
                                  comment: comments![index],
                                  onReport: (String reason) =>
                                      report(comments![index], reason),
                                  onLike: (int like) => changeLike(like, index),
                                  onDelete: () =>
                                      delete(comments![index], index),
                                  onReply: () => reply(comments![index]),
                                ),
                              );
                            }),
                      ),
                      const FooterLocator.sliver()
                    ],
                  );
                },
              ),
            ),
            CommentInput(
              isSecondary: true,
              focusNode: inputFocus,
              secondaryAt: commentAt?.userName,
              onSend: sendChat,
            )
          ],
        ),
      ),
    );
  }
}
